package com.example.mylogin.util;

import org.springframework.util.DigestUtils;

import java.security.SecureRandom;

/**
 * <p>
 * 功能描述：password工具类
 * </p>
 *
 * @author cui haida
 * @date 2025/05/30/8:54
 */
public class PasswordUtils {
    private static final SecureRandom RANDOM = new SecureRandom();
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    /**
     * 生成随机盐值
     */
    public static String generateSalt(int length) {
        StringBuilder sb = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            sb.append(CHARACTERS.charAt(RANDOM.nextInt(CHARACTERS.length())));
        }
        return sb.toString();
    }

    /**
     * 加密密码
     */
    public static String encryptPassword(String password, String salt) {
        return DigestUtils.md5DigestAsHex((password + salt).getBytes());
    }

    /**
     * 验证密码
     */
    public static boolean verifyPassword(String password, String salt, String encryptedPassword) {
        return encryptPassword(password, salt).equals(encryptedPassword);
    }
}
